<template>
    <n-form ref="formRef" :model="formData" v-bind="mergedProps">
        <GetanFormItem v-for="formItem in items" v-bind="formItem">
            <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
                <slot :name="item" v-bind="data ?? {}"></slot>
            </template>
        </GetanFormItem>
    </n-form>
</template>

<script setup lang="ts">
import { FormInst } from "naive-ui"
import { GetanFormProps } from "./types"
import { isUndefined } from "@/utils"
import { useFormData } from "./hooks/useFormData"
import { useFormItem } from "./hooks/useFormItem"
import { GetanFormItem } from "../components/FormItem"

const formRef = ref<FormInst | null>(null)

const props = defineProps<{ options?: GetanFormProps }>({})
const attrs = useAttrs()
const propsRef = ref<Partial<GetanFormProps>>({})

const mergedOptions = computed(() => {
    return {
        ...(props.options ?? {}),
        ...unref(propsRef)
    } as GetanFormProps
})

const mergedProps = computed(() => {
    return {
        ...attrs,
        ...parseProps(mergedOptions)
    }
})

function parseProps(options: Ref<GetanFormProps>) {
    const { inline, labelWidth } = unref(options)
    const result: Recordable = {}
    if (!isUndefined(inline)) {
        result.inline = inline
    }
    if (!isUndefined(labelWidth)) {
        result.labelWidth = labelWidth
    }
    return result
}

const { formData, getFormData, setFormData } = useFormData()
const { items } = useFormItem(mergedOptions, formData)

const emits = defineEmits(["register", "finish"])
</script>
